<template>
  <div ref="chartContainer" class="two-d-colume-chart-container"></div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch, nextTick, computed } from 'vue';
import * as echarts from 'echarts';
import type { ECharts, EChartsOption } from 'echarts';
import { formatSampletime } from "@/utils/appCommon/timeUtil";

// 定义设备数据类型
interface DeviceData {
  deviceId: string;
  deviceName: string;
  data: Array<{ x: number; y: number }>;
  color?: string;
}

// 定义组件 props
const props = defineProps({
  title: {
    type: String,
    default: ''
  },
  xAxisField: {
    type: String,
    default: ''
  },
  xAxisUnit: {
    type: String,
    default: ''
  },
  yAxisField: {
    type: String,
    default: ''
  },
  yAxisUnit: {
    type: String,
    default: ''
  },
  devicesData: {
    type: Array<DeviceData>,
    required: true
  },
  showToolbar: {
    type: Boolean,
    default: true
  },
  showZoom: {
    type: Boolean,
    default: true
  },
  autoRangePadding: {
    type: Number,
    default: 0.1 // 坐标轴自动范围的内边距比例
  },
});

// 定义组件 emits
const emit = defineEmits<{
  (e: 'barClick', params: any): void
}>();

// 图表容器引用
const chartContainer = ref<HTMLDivElement | null>(null);
// 图表实例引用
let chartInstance: ECharts | null = null;

// 计算所有数据的x轴范围
const xAxisRange = computed(() => {
  const allXValues: number[] = [];
  props.devicesData.forEach(device => {
    device.data.forEach(point => {
      allXValues.push(point.x);
    });
  });

  if (allXValues.length === 0) return { min: 0, max: 100 };

  const min = Math.min(...allXValues);
  const max = Math.max(...allXValues);
  const range = max - min;

  // 添加适当的内边距
  return {
    min: min - range * props.autoRangePadding,
    max: max + range * props.autoRangePadding
  };
});

// 计算所有数据的y轴范围
const yAxisRange = computed(() => {
  const allYValues: number[] = [];
  props.devicesData.forEach(device => {
    device.data.forEach(point => {
      allYValues.push(point.y);
    });
  });

  if (allYValues.length === 0) return { min: 0, max: 100 };

  const min = Math.min(...allYValues);
  const max = Math.max(...allYValues);
  const range = max - min;

  // 确保y轴从0开始，更符合柱形图的展示习惯
  const adjustedMin = Math.min(0, min - range * props.autoRangePadding);

  // 添加适当的内边距
  return {
    min: adjustedMin,
    max: max + range * props.autoRangePadding
  };
});

// 窗口大小变化处理函数
const handleResize = () => {
  if (chartInstance) {
    chartInstance.resize();
  }
};

// 初始化图表
const initChart = () => {
  if (!chartContainer.value || props.devicesData.length === 0) {
    return;
  }

  // 准备系列数据
  const seriesData = props.devicesData.map((device) => ({
    name: device.deviceName,
    type: 'bar' as const,
    data: device.data.map(point => [point.x, point.y]),
    itemStyle: {
      color: device.color || undefined
    },
    emphasis: {
      itemStyle: {
        shadowBlur: 10,
        shadowOffsetX: 0,
        shadowColor: 'rgba(0, 0, 0, 0.5)'
      }
    },
    label: {
      show: true,
      position: 'top',
      formatter: function(params: any) {
        // 只在柱子顶部显示数值
        return params.value[1];
      }
    }
  }));

  // 准备图表配置
  const option: EChartsOption = {
    title: {
      text: props.title,
      left: 'center',
      textStyle: {
        fontSize: 18
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: function(params: any) {
        if (!params || params.length === 0) return '';

        // 获取x轴值
        const xValue = params[0].value[0];
        let xDisplay = xValue;

        // 处理微秒级时间戳
        if (props.xAxisField === 'sampletime') {
          xDisplay = formatSampletime(xValue)
        }

        let result = `X: ${xDisplay}`;
        params.forEach((param: any) => {
          result += `<br/>${param.marker} ${param.seriesName}: ${param.value[1]}`;
        });
        return result;
      }
    },
    legend: {
      data: props.devicesData.map(device => device.deviceName),
      bottom: props.showZoom ? 30 : 10
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: props.showZoom ? '15%' : '10%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'value' as const,
      name: props.xAxisUnit ? `X轴 (${props.xAxisUnit})` : 'X轴',
      nameLocation: 'middle',
      nameGap: 30,
      min: xAxisRange.value.min,
      max: xAxisRange.value.max,
      splitLine: {
        show: true,
        lineStyle: {
          color: '#eee'
        }
      }
    },
    yAxis: {
      type: 'value' as const,
      name: props.yAxisUnit ? `Y轴 (${props.yAxisUnit})` : 'Y轴',
      nameLocation: 'middle',
      nameGap: 40,
      min: yAxisRange.value.min,
      max: yAxisRange.value.max,
      splitLine: {
        show: true,
        lineStyle: {
          color: '#eee'
        }
      }
    },
    series: seriesData,
    toolbox: props.showToolbar ? {
      feature: {
        saveAsImage: {
          title: '保存图片',
          pixelRatio: 2
        },
        dataZoom: {
          title: {
            zoom: '区域缩放',
            back: '取消缩放'
          }
        },
        restore: {
          title: '还原'
        }
      },
      right: 10
    } : undefined,
    dataZoom: props.showZoom ? [{
      type: 'slider',
      show: true,
      xAxisIndex: [0],
      bottom: 0
    }, {
      type: 'inside',
      xAxisIndex: [0]
    }] : undefined
  };

  // 创建图表实例
  chartInstance = echarts.init(chartContainer.value);

  // 设置图表配置
  chartInstance.setOption(option);

  // 绑定点击事件
  chartInstance.on('click', (params: any) => {
    if (params.data && Array.isArray(params.data)) {
      const barData = {
        ...params,
        deviceId: props.devicesData.find(device => device.deviceName === params.seriesName)?.deviceId,
        x: params.data[0],
        y: params.data[1]
      };
      emit('barClick', barData);
    }
  });
};

// 监听 props 变化，更新图表
watch([
  () => props.title,
  () => props.xAxisUnit,
  () => props.yAxisUnit,
  () => props.devicesData,
  () => props.showToolbar,
  () => props.showZoom,
  () => props.autoRangePadding,
  () => props.barWidth
], () => {
  if (chartInstance) {
    initChart();
  }
}, { deep: true });

// 组件挂载时初始化图表和事件监听
onMounted(() => {
  nextTick(() => {
    initChart();
    window.addEventListener('resize', handleResize);
  });
});

// 组件卸载时清理图表和事件监听
onUnmounted(() => {
  if (chartInstance) {
    chartInstance.dispose();
    chartInstance = null;
  }
  window.removeEventListener('resize', handleResize);
});
</script>

<style scoped lang="scss">
.two-d-colume-chart-container {
  width: 100%;
  height: 100%;
  min-height: 200px;
  box-sizing: border-box;
}

// 自定义tooltip样式
:deep(.echarts-tooltip) {
  border-radius: 4px;
  border: 1px solid #ddd;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  padding: 8px;
  background-color: rgba(255, 255, 255, 0.95);
}
</style>
